﻿#include "YDemuxerTask.h"
#include <QDebug>


extern "C"
{
#include <libavformat/avformat.h>
}
using namespace std;

bool YDemuxerTask::Open(std::string url, int timeout_ms)
{

    LOGDEBUG("XDemuxTask::Open begin!");
    demuxer_.Close();//断开之前的连接
    this->url_ = url;
    this->timeout_ms_ = timeout_ms;
    auto c = demuxer_.Open(url.c_str());
    if (!c)return false;
    demuxer_.setContext(c);
    demuxer_.set_time_out_ms(timeout_ms);//设置超时时间
    LOGDEBUG("XDemuxTask::Open end!");
    return true;
}
void YDemuxerTask::Working()
{
    AVPacket pkt;
    while (!isExit_)
    {
        //如果视频暂停了就停止解封装
        if (isPause())
        {
            MSleep(1);
            continue;
        }

        if (!demuxer_.Read(&pkt))
        {
            //读取失败
            LOGDEBUG("-");
            if (!demuxer_.is_connected())
            {
                Open(url_, timeout_ms_);
            }

            this_thread::sleep_for(1ms);
            continue;
        }
        //播放速度控制
        LOGDEBUG(".");
        if (syn_type_ == YSYN_VIDEO &&
            pkt.stream_index == demuxer_.GetVideoIndex())
        {
            auto dur = demuxer_.RescaleToMs(pkt.duration, pkt.stream_index);
            if (dur <= 0)
                dur = 40;
            //pkt.duration
            MSleep(dur);
        }
        Next(&pkt);
        av_packet_unref(&pkt);

        this_thread::sleep_for(1ms);
    }
}

bool YDemuxerTask::Seek(long long ms)
{
    auto vp = demuxer_.CopyVideoParameters();
    if (!vp)return false;
    auto pts = av_rescale_q(ms, { 1,1000 }, *vp->time_base);
    return demuxer_.Seek(pts, getVideoIndex());
}


YDemuxerTask::YDemuxerTask()
{

}

YDemuxerTask::~YDemuxerTask()
{
}
